package org.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.order.entity.CartItem;
import org.example.order.entity.Good;
import org.example.order.entity.Order;
import org.example.order.entity.User;
import org.example.order.mapper.CartItemMapper;
import org.example.order.service.CartService;
import org.example.order.service.GoodService;
import org.example.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodService goodService;

    @Override
    public void addToCart(Long userId, Long productId, Integer quantity) {
        // 检查用户是否存在
        User user = userService.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 检查商品是否存在
        Good good = goodService.getGood(productId);
        if (good == null) {
            throw new IllegalArgumentException("商品不存在");
        }

        // 检查购物车中是否已经存在该用户的该商品记录
        QueryWrapper<CartItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("product_id", productId);
        CartItem cartItem = cartItemMapper.selectOne(queryWrapper);

        if (cartItem != null) {
            // 如果记录存在，更新数量
            cartItem.setQuantity(cartItem.getQuantity() + quantity);
            cartItem.setTotalPrice(good.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())));
            cartItemMapper.updateById(cartItem);
        } else {
            // 如果记录不存在，插入新的记录
            cartItem = new CartItem();
            cartItem.setUserId(userId);
            cartItem.setProductId(productId);
            cartItem.setQuantity(quantity);
            cartItem.setPrice(good.getPrice());
            cartItem.setName(good.getName());
            cartItem.setTotalPrice(good.getPrice().multiply(BigDecimal.valueOf(quantity)));
            cartItemMapper.insert(cartItem);
        }
    }

    @Override
    public void updateQuantity(Long userId, Long productId, Integer quantity) {
        QueryWrapper<CartItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("product_id", productId);
        CartItem cartItem = cartItemMapper.selectOne(queryWrapper);
        if (cartItem != null) {
            cartItem.setQuantity(quantity);
            cartItemMapper.updateById(cartItem);
        }
    }

    @Override
    public void removeFromCart(Long userId, Long productId) {
        QueryWrapper<CartItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("product_id", productId);
        cartItemMapper.delete(queryWrapper);
    }

    @Override
    public List<CartItem> getCartList(Long userId) {
        return cartItemMapper.selectByUserId(userId);
    }

    @Override
    public void clearCart(Long userId) {
        cartItemMapper.deleteByUserId(userId);
    }

    @Override
    public Order submitOrder(Long userId, String receiverAddress, String receiverName, String receiverPhone, String remark) {
        List<CartItem> cartItems = getCartList(userId);
        Order order = new Order();
        order.setUserId(userId);
        order.setStatus("1");
        order.setOrderTime(LocalDateTime.now().toString());
        order.setOrderNumber(String.valueOf(System.currentTimeMillis()));
        BigDecimal totalAmount = BigDecimal.ZERO;
        StringBuilder gwc = new StringBuilder();
        for (CartItem item : cartItems) {
            totalAmount = totalAmount.add(item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
            gwc.append(item.getProductId()).append(":").append(item.getQuantity()).append(";");
        }
        order.setGwc(gwc.toString());
        order.setAmount(totalAmount.toString());
        order.setReceiverAddress(receiverAddress);
        order.setReceiverName(receiverName);
        order.setReceiverPhone(receiverPhone);
        order.setRemark(remark);
        orderService.add(order);
        //clearCart(userId);
        return order;
    }
}